﻿package component.validate.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Properties;

/**
 * 读取后缀名为properties文件的工具类
 *
 */
public class PropertiesUtil {	
	private static Object obj = new Object();
	private static PropertiesUtil instance = null;
	
	private static String file = "/validate.properties";
	
	private PropertiesUtil(){
		
	}
	
	public static PropertiesUtil getInstance() {
		// 双重检查（JVM类载入两次）
		if (instance == null) {
			synchronized (obj) {
				if (instance == null) {
					instance = new PropertiesUtil();
				}
			}
		}
		return instance;

	}
	
	public static Properties properties = null;
	public static Properties getProperties(String fileName){
		//需要去掉substring(1)，因为在Linux下全部路径是以 / 开头的
		//String path = this.getClass().getResource(fileName).getPath().substring(1);
		//String path = this.getClass().getResource(fileName).getPath();
		//System.out.println("path = " + path);
		InputStream inStream = null;
		try {
			//inStream = new FileInputStream(path);//有中文乱码
			inStream = PropertiesUtil.class.getResourceAsStream(fileName);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		Properties p=new Properties();
		try {
			p.load(inStream);
			//p.load(PropertiesUtil.class.getResourceAsStream(fileName));
			//p.loadFromXML(inStream);
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		return p;
	}
	
	public static Properties getProperties(){
		if(properties==null)
			properties = getProperties(file);
		return properties;
	}
	
	public static String getProperty(String key){
		Properties p = getProperties();
		return p.getProperty(key);
	}
	
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成方法存根
		PropertiesUtil pro = PropertiesUtil.getInstance();
		Properties p = pro.getProperties();
		System.out.println(p.getProperty("db_type"));
	}

}
